﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.Linq;
using System.Linq;
using System.Text;
using IntraVision.Web;
using IntraVision.Web.Filter;
using IntraVision.Web.Security;
using Model;

[AllowedRole("IsAdmin")]
public class UserController : TableController<NotarialServiceDataContext, User>
{
    bool create = false;

    public UserController() {}

    protected override void BeforeSubmit(NotarialServiceDataContext dc, User user)
    {
        create = (user.Id == 0);

        if (!string.IsNullOrEmpty(Request["password"]))
            user.Password = RequestHelper.MD5Encode(Request["password"]);

        int[] pids = RequestHelper.GetIdsFromString(Request["pid"]);
        user.UserPermissions.UpdateEntitySet("PermissionId", pids, dc);
    }

    protected override void AfterSubmit(NotarialServiceDataContext dc, User entity)
    {
        Logger.WriteLog(dc, (create) ? LogOperationType.UserCreate : LogOperationType.UserChange, (Session["User"] as User).Id, null, null);
    }

    protected override void EntityDeleted(NotarialServiceDataContext dc, List<User> deleted)
    {
        foreach (var entity in deleted)
            Logger.WriteLog(dc, LogOperationType.UserDelete, (Session["User"] as User).Id, null, null);
    }

    protected override void EntityLoaded(NotarialServiceDataContext dc, User entity)
    {
        if (!String.IsNullOrEmpty(Request["popup"]))
        {
            ViewData["popup"] = true;
            ViewData["readonly"] = true;
            LayoutPath = "~/views/layouts/popup.haml";
        }
        ViewData["roles"] = (from r in dc.Roles select r);
        ViewData["notarialregisters"] = (from nr in dc.NotarialRegisters where !nr.IsArchive select nr);
        if (entity.Id > 0)
        {
            ViewData["permissions"] = (from p in dc.Permissions where (int)PermissionGroupType.System == p.GroupId orderby p.Id select p).ToList();
            ViewData["financepermissions"] = (from p in dc.Permissions where (int)PermissionGroupType.Finance == p.GroupId select p).ToList();
            ViewData["userpermissions"] = (from up in entity.UserPermissions orderby up.Permission.PermissionGroup.Id select up.PermissionId).ToArray();
        }
        ViewData["user"] = Session["user"] as User;
    }

    [AllowedRole("UserAdmin")]
    public void UsersPermissions()
    {
        RegisterScript("userpermission/userpermission.js");

        using (var dc = new NotarialServiceDataContext())
        {
            ViewData["permissions"] = (from p in dc.Permissions where (int)PermissionGroupType.System == p.GroupId select p).ToList();
            ViewData["financepermissions"] = (from p in dc.Permissions where (int)PermissionGroupType.Finance == p.GroupId select p).ToList();
            ViewData["users"] = (from u in dc.Users orderby u.LastName, u.Name select u).ToList();
            ViewData["userspermissions"] = (from up in dc.UserPermissions select up).ToList();
        }

        TemplatePath = "~/views/user/userspermissions.haml";
        LayoutPath =  "~/views/layouts/page.haml";

        if (!String.IsNullOrEmpty(Request["nolayout"]))
            LayoutPath = "none";

        RenderView();
    }

    //Преобразуем данные с сервера к выходному типу данных.
    protected override IQueryable ConvertQueryToResult(NotarialServiceDataContext dc, IQueryable<User> query)
    {
        return (from u in query
                select new
                {
                    Id = u.Id,
                    RoleId = u.RoleId,
                    FIO = u.FIO,
                    Name = u.Name,
                    FullName = u.FullName,
                    LastName = u.LastName,
                    Login = u.Login,
                    Password = u.Password,
                    Email = u.Email,
                    Phone = u.Phone,
                    Comments = u.Comments,
                    IsArchive = u.IsArchive,
                    RoleName = u.Role.Name
                });
    }

    //Создаем условия фильтров вручную. Создание фильтров через XML пока не поддерживается.
    protected override void CreateFilterConditions(NotarialServiceDataContext dc)
    {
        Filter = new Filter<User>();
        Filter.Conditions.Add(new NumericFilterCondition<User>("Id", "Номер"));
        Filter.Conditions.Add(new StringFilterCondition<User>("Name", "ФИО"));
        Filter.Conditions.Add(new StringFilterCondition<User>("Login", "Логин"));
        Filter.Conditions.Add(new SelectFilterCondition<User>("RoleId", "Роль", (from r in dc.Roles orderby r.Name select r)));
        Filter.Conditions.Add(new BoolFilterCondition<User>("IsArchive", "Архивный"));
    }

    public void Select()
    {
        ViewData["popup"] = true;
        RegisterScript("table.js", "jquery.multipleselect.js", "user/select.js");

        _ActionKey = Action;
        if (String.IsNullOrEmpty(Request["nolayout"]))
        {
            LayoutPath = "~/views/layouts/popup.haml";
            TemplatePath = "~/views/user/select.haml";
        }
        else TemplatePath = "~/views/_table/table.haml";

        ProcessTable();
    }

    [AllowedRole("UserAdmin")]
    public override void Create()
    {
        base.Create();
    }

    [AllowedRole("UserAdmin")]
    public override void Delete()
    {
        base.Delete();
    }

    [AllowedRole("UserAdmin")]
    public override void List()
    {
        base.List();
    }

    public override void View(string entityid)
    {
        if (String.IsNullOrEmpty(Request["popup"]) && !(Session["user"] as IUser).HasPermission("UserAdmin"))
            throw new IntraVisionWebException(404);
        base.View(entityid);
    }
}